package com.supereye.platform.web.user.service;

import java.io.File;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.codehaus.jackson.type.TypeReference;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.StringUtils;
import com.supereye.platform.common.PageData;
import com.supereye.platform.interfaces.BzClient;
import com.supereye.platform.util.BeanUtil;
import com.supereye.platform.util.EncodeUtil;
import com.supereye.platform.util.ExcelUtil;
import com.supereye.platform.util.JacksonUtil;
import com.supereye.platform.util.PropUtil;
import com.supereye.platform.web.user.dao.UserDao;
import com.supereye.platform.web.user.model.TopUser;

@Service
public class UserService {

	@Resource
	private UserDao userDao;

	public void addUser(TopUser user) throws Exception{
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		user.setCreateDate(format.format(new Date()));
		
		user.setStatus("1");//启用
		
		int num = userDao.getUserNumByAccount(user.getAccount());
		if(num > 0){
			throw new Exception("用户账号["+user.getAccount()+"]已存在，不允许重复添加");
		}
		
		user.setPassword(EncodeUtil.toMd5(user.getPassword()));
		userDao.addUser(user);
		
		String relateId = this.addBzUser(user);
		user.setRelateId(relateId);
		//设置管理ID
		this.userDao.updateRelateId(user);
	}
	
	private String addBzUser(TopUser user)throws Exception{
		long result = BzClient.getClient().queryUserAccountExisted(user.getAccount());
		if(result > 0){
			throw new Exception("该用户已存在");
		}
		
		Document document = DocumentHelper.createDocument();	
		Element root = document.addElement("xml");  
		root.addElement("birthdady").setText(this.formatBirthDay(user.getBirthDay()));
		root.addElement("sex").setText(this.formatField(user.getSex()));
		root.addElement("address").setText(this.formatField(user.getAddress()));
		root.addElement("email").setText(this.formatField(user.getEmail()));
		root.addElement("nickname").setText(this.formatField(user.getName()));
		root.addElement("job").setText(this.formatField(user.getPosition()));
		root.addElement("account").setText(this.formatField(user.getAccount()));
		root.addElement("password").setText(this.formatField(user.getPassword()));
		root.addElement("mobile").setText(this.formatField(user.getPhone()));
		String xml = document.getRootElement().asXML();
		
		//添加用户
		long userId = BzClient.getClient().addUser(xml);
		//添加到部门
		BzClient.getClient().addDeparmtmentUser(userId, 0, 2, 0);
		
		Document document2 = DocumentHelper.createDocument();	
		Element root2 = document2.addElement("xml"); 
		Element userEle = root2.addElement("user");
		userEle.addElement("sip").setText("1");
		userEle.addElement("email").setText("1");
		userEle.addElement("userid").setText(String.valueOf(userId));
		userEle.addElement("vod").setText("1");
		userEle.addElement("conf").setText("1");
		userEle.addElement("sms").setText("1");
		userEle.addElement("fbox").setText("1");
		userEle.addElement("mix").setText("1");
		userEle.addElement("live").setText("1");
		
		String xml2 = document2.getRootElement().asXML();
		//添加权限
		BzClient.getClient().addUserPermission(xml2);
		
		return String.valueOf(userId);
	}
	
	private String formatField(String value){
		if(StringUtils.isEmpty(value)){
			return "";
		}
		return value;
	}
	
	private String formatBirthDay(String birthDay) throws Exception {
		if(StringUtils.isEmpty(birthDay) || "null".equals(birthDay)){
			return "";
		}else{
			DateFormat res = new SimpleDateFormat("MM/dd/yyyy");
			DateFormat des = new SimpleDateFormat("yyyy-MM-dd");
			return des.format(res.parse(birthDay));
		}
		
	}
	
	
	public static void main(String[] args) {
		Document document = DocumentHelper.createDocument();	
		Element root = document.addElement("xml");  
		root.addElement("birthdady").setText("2012/12/12");
		root.addElement("sex").setText("男");
		System.out.println(root.asXML());
	}

	public String getUserList(Integer pageNum,Integer pageSize,TopUser user) throws Exception{
		Map<String,Object> params = BeanUtil.beanToMap(user);
		Integer count = userDao.getUserListCount(params);
		
		params.put("pageFlag", "1");
		params.put("fromNum", (pageNum-1)*pageSize);
		params.put("pageSize", pageSize);
		List<TopUser> list = userDao.getUserList(params);
		
		PageData<TopUser> pageData = new PageData<TopUser>();
		pageData.setTotal(count);
		pageData.setRows(list);
		return JacksonUtil.toJSon(pageData);
	}

	public void deleteUsers(String[] userIds) throws Exception{
		userDao.deleteUsers(userIds);
		
	}

	public String exportUsers(MultipartFile file) throws Exception {
		String tmpPath = PropUtil.get("upload.tmp.url");
		String path=tmpPath+new Date().getTime()+"_"+file.getOriginalFilename();
		if(StringUtils.isEmpty(file.getOriginalFilename())){
			throw new Exception("请选择文件");
		}
		if(!file.getOriginalFilename().toLowerCase().endsWith(".xlsx") && !file.getOriginalFilename().toLowerCase().endsWith(".xls")){
			throw new Exception("文件后缀名为.xlsx或者.xls");
		}
        File newFile=new File(path);
        if(!new File(tmpPath).isDirectory()){
        	new File(tmpPath).mkdirs();
        }
        file.transferTo(newFile);
        
        //读取临时文件的EXCEL文件
        List<Map<Integer,Object>> list = ExcelUtil.readExcel(path);
        
        File usedFile = new File(path);
        usedFile.delete();
        
        List<TopUser> result = new ArrayList<TopUser>();
        TopUser user = null;
        for(Map<Integer,Object> map:list){
        	user = new TopUser();
        	user.setAccount(getStringValue(map,0));
        	user.setPassword(getStringValue(map,1));
        	user.setName(getStringValue(map,2));
        	user.setPhone(getStringValue(map,3));
        	user.setSex(getStringValue(map,4));
        	user.setBirthDay(getStringValue(map,5));
        	user.setEmail(getStringValue(map,6));
        	user.setPosition(getStringValue(map,7));
        	user.setAddress(getStringValue(map,8));
        	user.setTerminalId(getIntgerValue(map,9));
        	user.setKnowledge(getStringValue(map,10));
        	result.add(user);
        }
        
        PageData<TopUser> pageData = new PageData<TopUser>();
        pageData.setRows(result);
        return JacksonUtil.toJSon(pageData);
	}
	
	public String getStringValue(Map<Integer,Object> map,Integer key){
		if(map!=null){
			if(map.get(key) != null){
				return String.valueOf(map.get(key));
			}else{
				return null;
			}
		}else{
			return null;
		}
	}
	
	public Integer getIntgerValue(Map<Integer,Object> map,Integer key){
		try{
			if(map!=null){
				String value = (String) map.get(key);
				if(!StringUtils.isEmpty(value)){
					BigDecimal bd = new BigDecimal(value);
					return bd.intValue();
				}else{
					return null;
				}
			}else{
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
	}

	public void confirmTempUsers(String userListString) throws Exception {
		List<TopUser> list = JacksonUtil.readValue(userListString, new TypeReference<List<TopUser>>(){});
		for(TopUser user:list){
			this.addUser(user);
		}
	}

	public void updateUser(TopUser user) throws Exception{
		userDao.updateUser(user);
	}

	public String getExpertsByUserAccount(String userAccount) throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			TopUser user = userDao.getUserByAccount(userAccount);
			if(user==null){
				TopUser newUser = new TopUser();
				newUser.setName(userAccount);
				newUser.setAccount(userAccount);
				newUser.setPassword("111111");//初始密码
				newUser.setOrgId(1);//初始机构
				this.addUser(newUser);
				
			}
			
			List<String> list = userDao.getExpertsByUserAccount(userAccount);

			
			map.put("dealFlag", "1");
			map.put("result", list);
			
			return JacksonUtil.toJSon(map);
		}catch(Exception e){
			e.printStackTrace();
			map.put("dealFlag", "0");
			return JacksonUtil.toJSon(map);
		}
		
	}

	public String getExpertsByUserId(String userId) throws Exception {
		List<String> list = userDao.getExpertsByUserId(userId);
		return JacksonUtil.toJSon(list);
	}

	public String getExpertNamesById(String expertIds) throws Exception {
		return userDao.getExpertNamesById(expertIds);
	}

}
